<?php

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Helpers\Code;
use App\Models\Common\Password;
use Illuminate\Support\Facades\Validator;

class ForgotPasswordController extends Controller
{

    public function __construct()
    {
        $this->rules = [
            'password' => 'required|alpha_dash|between:6,16|confirmed',
            'code' => 'bail|required|alpha_dash|between:6,6',
            'communication' => 'bail|required|max:100',
        ];

        $this->messages = [
            'password.required' => trans('user.password_required'),
            'password.alpha_dash' => trans('user.password_alpha_dash'),
            'password.between' => trans('user.password_between'),
            'password.confirmed' => trans('user.password_confirmed'),
            'code.required' => trans('common.code_required'),
            'code.alpha_dash' => trans('common.code_alpha_dash'),
            'code.between' => trans('common.code_between'),
            'communication.required' => trans('user.communication_required'),
            'communication.max' => trans('user.communication_max'),
        ];

        $this->model = new Password();
    }

    /**
     * 发送验证码
     * @param Request $request
     * @return array
     */
    public function sendCode(Request $request)
    {
        try {
            $contact = $request->only(['communication', 'type']);

            $rules = [
                'communication' => 'bail|required|max:100',
                'type' => 'bail|required|max:50',
            ];
            $message = [
                'communication.required' => trans('user.communication_required'),
                'communication.max' => trans('user.communication_max'),
                'type.required' => trans('user.type_required'),
                'type.max' => trans('user.type_max'),
            ];

            $validator = Validator::make($contact, $rules, $message);
            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            $communicate = $contact['communication'];

            //判断是否是邮箱或者手机
            $checkMail = "/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
            $checkPhone = "/^(13[0-9]|14[57]|15[012356789]|17[0678]|18[0-9])[0-9]{8}$/";

            if ($contact['type'] === 'email') {
                $checkEmail = preg_match($checkMail, $communicate);
                if (!$checkEmail) {
                    return $this->error('common.format_error');
                }
                $data['type'] = 0;
                $userInfo = $this->model->checkEmailIsExist($communicate);
                $check = $userInfo['id'];
            } else if ($contact['type'] === 'mobile') {
                $checkEmail = preg_match($checkPhone, $communicate);
                if (!$checkEmail) {
                    return $this->error('common.format_error');
                }
                $data['type'] = 1;
                $userInfo = $this->model->checkPhoneIsExist($communicate);
                $check = $userInfo['id'];
            } else {
                return $this->error('common.format_error');
            }

            //判断用户是否存在
            if (!$check) {
                return $this->error('common.user_not_exit');
            }

            $name = $userInfo['username'];
            //发送邮件
            if ($data['type'] == 0) {
                //获取随机字符串
                $code = getRandomString(6);

                Mail::send('emails.email', ['code' => $code, 'name' => $name], function ($message) use ($communicate) {
                    $to = $communicate;
                    $message->from(env('MAIL_USERNAME'), '卡替医疗');
                    $message->to($to)->subject('修改密码');
                });

                //判断邮件是否发送成功
                $error = Mail::failures();
                if (empty($error)) {
                    $data['code'] = $code;
                    $data['expiration_time'] = now()->addMinutes(5);
                    $data['communication'] = $communicate;
                    $data['user_id'] = $check;
                    $res = $this->model->addCode($data);
                    if (!$res) {
                        return $this->error('common.add_failure');
                    }
                } else {
                    return $this->error('common.send_communicate_fail');
                }
            } else {
                /**
                 * todo: 手机验证码找回密码
                 */
            }
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 通过验证码修改密码
     * @param Request $request
     * @return array
     */
    public function resetPassword(Request $request)
    {
        try {
            $data = $request->only(['communication', 'password', 'password_confirmation', 'code']);

            $validator = Validator::make($data, $this->rules, $this->messages);
            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            //验证码或帐号错误
            $check = $this->model->getCodeInfo($data);
            if (!$check) {
                return $this->error('common.code_or_account_error');
            }

            //判断验证码是否失效
            $time = now();
            $expire = $check['expiration_time'];
            if ($time > $expire) {
                return $this->error('common.time_over_top');
            }

            $data['password'] = e(Hash::make($data['password']));

            if ($data['code'] != $check['code']) {
                return $this->error('common.code_different_error');
            }

            $res = $this->model->editPassword($data, $check);

            if (!$res) {
                return $this->error('common.edit_failure');
            }

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

}
